import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { validateFormGroup } from '@core/util/validate-utils';
import { formatDate } from '@core/util/date-utils';
import { isDate } from 'util';
import { myValidNull } from '@core/util/string-utils';

@Component({
  selector: 'base-form',
  templateUrl: './base-form.component.html',
  styles: [`
    ::ng-deep .ant-card-body {
      padding: 12px 24px 12px 24px;
    }
  `],
})
export class BaseFormComponent implements OnInit {

  @Input() params: any = {};
  @Input() index: any;
  @Output() entityChanges = new EventEmitter();

  formErrors: any = { name: '', value: '' };
  validateForm: FormGroup;
  entity: any = {};
  isSaving: boolean = false;


  valueObj: any = {};

  constructor(private fb: FormBuilder,
              private message: NzMessageService) {
  }

  ngOnInit() {
    this.entity = this.params[this.index];
    this.initValidateForm();
  }


  initValidateForm() {
    this.validateForm = this.fb.group({
      name: [this.entity.name, [Validators.required]],
      value: [this.entity.value, [Validators.required]],
      useless: [null, []],
    });
  }


  submitForm() {
    if (this.validateForm.invalid) {
      console.log('表单有错');
      this.formErrors = validateFormGroup(this.validateForm, this.formErrors, true);
      for (const i in this.validateForm.controls) {
        this.validateForm.controls[i].markAsDirty();
        this.validateForm.controls[i].updateValueAndValidity();
      }
    } else {
      let $this = this;
      // console.log(this.validateForm);
      this.entity.name = this.validateForm.controls.name.value;
      this.entity.value = this.validateForm.controls.value.value;
      if (this.entity.type == 'json') {
        this.valueObj = JSON.parse(this.entity.value);
        let keys = Object.keys($this.valueObj);
        if (!keys || keys.length <= 0) {
          this.message.error('请至少添加一组【' + this.entity.name + '】的配置值');
          return false;
        }
        for (let k of keys) {
          if (!k) {
            this.message.error('配置值键名不能为空');
            return false;
          }
          if (!$this.valueObj[k]) {
            this.message.error('配置值【' + k + '】的键值不能为空');
            return false;
          }
        }
      }

      if (this.entity.type == 'json-array') {
        let valueObjArr = JSON.parse(this.entity.value);
        if (!valueObjArr || valueObjArr.length <= 0) {
          this.message.error('请至少添加一组【' + this.entity.name + '】的配置值');
          return false;
        }
        for (const arr of valueObjArr) {
          if(!arr.key || myValidNull(arr.key.toString().replace(/\s+/g,''))){
            this.message.error('配置值键名不能为空');
            return false;
          }
          if(!arr.value || myValidNull(arr.value.toString().replace(/\s+/g,''))){
            this.message.error('配置值【' + arr.key + '】的键值不能为空');
            return false;
          }
        }
      }
      if(this.entity.type == 'date'){
        if(isDate(this.entity.value)){
          this.entity.value = formatDate(this.entity.value,"yyyy-MM-dd 23:59:59");
        }
      }

      this.isSaving = true;
      // console.log('表单ok了');
      // console.log(this.entity);
      this.params[this.index] = this.entity;

      this.entityChanges.emit(this.entity);
    }
  }


}
